package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.IUserService;
import com.itheima.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.itheima.util.RedisConstants.*;

/**
 * @author Yzq
 * @date 2022/10/10
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result login(User user) {
        //根据用户输入的手机号查找用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,user.getPhone());
        User one = userMapper.selectOne(lqw);
        //判断用户是否存在
        if (one == null){
            //不存在，需要创建新用户
            int r = userMapper.insert(user);
            if (r<=0){
                return Result.error("用户不存在，并且创建失败!");
            }
            User one1 = userMapper.selectOne(lqw);
            //登录成功，将用户的id存入redis中
            stringRedisTemplate.opsForValue().set(LOGIN_USER_KEY,one1.getId().toString());
            //设置有效期
            stringRedisTemplate.expire(LOGIN_USER_KEY,LOGIN_CODE_TTL, TimeUnit.MINUTES);
            return Result.success(user);
        }
        //存在，登录成功
        //登录成功，将用户的id存入redis中
        stringRedisTemplate.opsForValue().set(LOGIN_USER_KEY,one.getId().toString());
        return Result.success(one);
    }

    @Override
    public Result logout() {
        //从redis中删除，当前用户登录的信息
//        stringRedisTemplate.delete(LOGIN_USER_KEY);
        return Result.success("退出登录");
    }
}
